<template>
  <div class="body1">
    <div class="no-print el-button-print">
      <el-button @click="exportPDF">导出为pdf</el-button>
    </div>
    <div class="body2" id="pdfDom" :class="{ 'pdf-export': isPdfExport }">
      <div class="title">
        <div class="biaotididian">{{ agencyName }}</div>
        <div class="biaoti">行政处罚决定法制审核意见表</div>
      </div>
      <table class="tableStyle">
        <colgroup>
          <col width="15%">
          <col width="42%">
          <col width="15%">
          <col width="7%">
          <col width="7%">
          <col width="7%">
          <col width="7%">
        </colgroup>
        <tbody>
          <tr>
            <td style="height: 30px; text-align: center;">案件名称</td>
            <td colspan="6">
              <el-input class="areaInputStyle" :resize="'none'" type="textarea" autosize v-model="this.form.textarea1"
                maxlength="27">
              </el-input>
            </td>
          </tr>
          <tr>
            <td style="height: 30px; text-align: center;">承办机构</td>
            <td colspan="6">
              <el-input class="areaInputStyle" :resize="'none'" maxlength="27" type="textarea" autosize
                v-model="this.form.textarea2">
              </el-input>
            </td>
          </tr>
          <tr>
            <td style="height: 30px; text-align: center;">送审人员</td>
            <td>
              <el-input class="areaInputStyle" :resize="'none'" maxlength="13" type="textarea" autosize
                v-model="this.form.textarea3">
              </el-input>
            </td>
            <td style="text-align: center;">送审时间</td>
            <td colspan="4">
              <editable-textarea :text="form.date1" param-type="YYYYMMDD1"
                @send-to-parent="receiveFromChild"></editable-textarea>
            </td>
          </tr>
          <tr>
            <td rowspan="10" style="text-align: center;">
              法制审核<br>内&nbsp;&nbsp;&nbsp;&nbsp;容
            </td>
            <td colspan="2" style="height: 30px;">行政执法主体是否合法</td>
            <td>是</td>
            <td @click="handleTdClick($event, '1', 'hefa')" style="text-align: center;">
              <span v-if="form.hefa === '1'" style="font-size: 5mm;">✓</span>
            </td>
            <td>否</td>
            <td @click="handleTdClick($event, '0', 'hefa')" style="text-align: center;">
              <span v-if="form.hefa === '0'" style="font-size: 5mm;">✓</span>
            </td>
          </tr>
          <tr>
            <td colspan="2" style="height: 30px;">行政执法人员是否具备执法资格</td>
            <td>是</td>
            <td @click="handleTdClick($event, '1', 'zige')" style="text-align: center;">
              <span v-if="form.zige === '1'" style="font-size: 5mm;">✓</span>
            </td>
            <td>否</td>
            <td @click="handleTdClick($event, '0', 'zige')" style="text-align: center;">
              <span v-if="form.zige === '0'" style="font-size: 5mm;">✓</span>
            </td>
          </tr>
          <tr>
            <td colspan="2" style="height: 30px;">是否超越本机关法定权限</td>
            <td>是</td>
            <td @click="handleTdClick($event, '1', 'qx')" style="text-align: center;">
              <span v-if="form.qx === '1'" style="font-size: 5mm;">✓</span>
            </td>
            <td>否</td>
            <td @click="handleTdClick($event, '0', 'qx')" style="text-align: center;">
              <span v-if="form.qx === '0'" style="font-size: 5mm;">✓</span>
            </td>
          </tr>
          <tr>
            <td colspan="2" style="height: 30px;">案件事实是否清楚</td>
            <td>是</td>
            <td @click="handleTdClick($event, '1', 'qc')" style="text-align: center;">
              <span v-if="form.qc === '1'" style="font-size: 5mm;">✓</span>
            </td>
            <td>否</td>
            <td @click="handleTdClick($event, '0', 'qc')" style="text-align: center;">
              <span v-if="form.qc === '0'" style="font-size: 5mm;">✓</span>
            </td>
          </tr>
          <tr>
            <td colspan="2" style="height: 30px;">证据是否合法充分</td>
            <td>是</td>
            <td @click="handleTdClick($event, '1', 'cf')" style="text-align: center;">
              <span v-if="form.cf === '1'" style="font-size: 5mm;">✓</span>
            </td>
            <td>否</td>
            <td @click="handleTdClick($event, '0', 'cf')" style="text-align: center;">
              <span v-if="form.cf === '0'" style="font-size: 5mm;">✓</span>
            </td>
          </tr>
          <tr>
            <td colspan="2" style="height: 30px;">适用法律、法规、规章是否准确</td>
            <td>是</td>
            <td @click="handleTdClick($event, '1', 'zq')" style="text-align: center;">
              <span v-if="form.zq === '1'" style="font-size: 5mm;">✓</span>
            </td>
            <td>否</td>
            <td @click="handleTdClick($event, '0', 'zq')" style="text-align: center;">
              <span v-if="form.zq === '0'" style="font-size: 5mm;">✓</span>
            </td>
          </tr>
          <tr>
            <td colspan="2" style="height: 30px;">适用裁量基准是否适当</td>
            <td>是</td>
            <td @click="handleTdClick($event, '1', 'sd')" style="text-align: center;">
              <span v-if="form.sd === '1'" style="font-size: 5mm;">✓</span>
            </td>
            <td>否</td>
            <td @click="handleTdClick($event, '0', 'sd')" style="text-align: center;">
              <span v-if="form.sd === '0'" style="font-size: 5mm;">✓</span>
            </td>
          </tr>
          <tr>
            <td colspan="2" style="height: 30px;">行政执法程序是否合法</td>
            <td>是</td>
            <td @click="handleTdClick($event, '1', 'hf')" style="text-align: center;">
              <span v-if="form.hf === '1'" style="font-size: 5mm;">✓</span>
            </td>
            <td>否</td>
            <td @click="handleTdClick($event, '0', 'hf')" style="text-align: center;">
              <span v-if="form.hf === '0'" style="font-size: 5mm;">✓</span>
            </td>
          </tr>
          <tr>
            <td colspan="2" style="height: 30px;">行政执法文书是否完备、规范</td>
            <td>是</td>
            <td @click="handleTdClick($event, '1', 'gf')" style="text-align: center;">
              <span v-if="form.gf === '1'" style="font-size: 5mm;">✓</span>
            </td>
            <td>否</td>
            <td @click="handleTdClick($event, '0', 'gf')" style="text-align: center;">
              <span v-if="form.gf === '0'" style="font-size: 5mm;">✓</span>
            </td>
          </tr>
          <tr>
            <td colspan="2" style="height: 30px;">违法行为是否涉嫌犯罪需要移送司法机关</td>
            <td>是</td>
            <td @click="handleTdClick($event, '1', 'jg')" style="text-align: center;">
              <span v-if="form.jg === '1'" style="font-size: 5mm;">✓</span>
            </td>
            <td>否</td>
            <td @click="handleTdClick($event, '0', 'jg')" style="text-align: center;">
              <span v-if="form.jg === '0'" style="font-size: 5mm;">✓</span>
            </td>
          </tr>
          <tr style="height: 145px;">
            <td style="text-align: center;">
              法制审核<br>人员意见
            </td>
            <td colspan="6" style="text-align: left;vertical-align: top; position: relative;">
              <el-input type="textarea" v-model="form.textarea4" :rows="textarea4Config.maxLines"
                @keydown.native="handleKeyDown('textarea4', $event)" @input="handleInput('textarea4', $event)"
                @paste.native="handlePaste('textarea4', $event)" class="el-textarea-hidden"
                style="white-space: pre;overflow-x: auto;font-family: monospace;" wrap="soft" />
              <div
                style="position: absolute; bottom: 10px; left: 20px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end; margin-top: 20px;">
                <div style="display: flex; align-items: flex-end;">
                  签名：
                  <SignatureField label="签名1" sign-type="sign1" :img-url="form.img1"
                    @update:imgUrl="form.img1 = $event" />
                </div>
                <div>
                  <editable-textarea :text="form.date2" param-type="YYYYMMDD2"
                    @send-to-parent="receiveFromChild"></editable-textarea>
                </div>
              </div>
            </td>
          </tr>
          <tr style="height: 145px;">
            <td style="text-align: center;">法制审核<br>机构负责<br>人&nbsp;意&nbsp;见</td>
            <td colspan="6" style="text-align: left;vertical-align: top; position: relative;">
              <el-input type="textarea" v-model="form.textarea5" :rows="textarea5Config.maxLines"
                @keydown.native="handleKeyDown('textarea5', $event)" @input="handleInput('textarea5', $event)"
                @paste.native="handlePaste('textarea5', $event)" class="el-textarea-hidden"
                style="white-space: pre;overflow-x: auto;font-family: monospace;" wrap="soft" />
              <div
                style="position: absolute; bottom: 10px; left: 20px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end; margin-top: 20px;">
                <div style="display: flex; align-items: flex-end;">
                  签名：
                  <SignatureField label="签名2" sign-type="sign2" :img-url="form.img2"
                    @update:imgUrl="form.img2 = $event" />
                </div>
                <div>
                  <editable-textarea :text="form.date3" param-type="YYYYMMDD3"
                    @send-to-parent="receiveFromChild"></editable-textarea>
                </div>
              </div>
            </td>
          </tr>
          <tr style="height: 125px;">
            <td style="text-align: center;">退卷确认<br>签&nbsp;&nbsp;&nbsp;&nbsp;字</td>
            <td colspan="6" style="text-align: left;vertical-align: top; position: relative;">
              <el-input type="textarea" v-model="form.textarea6" :rows="textarea6Config.maxLines"
                @keydown.native="handleKeyDown('textarea6', $event)" @input="handleInput('textarea6', $event)"
                @paste.native="handlePaste('textarea6', $event)" class="el-textarea-hidden"
                style="white-space: pre;overflow-x: auto;font-family: monospace;" wrap="soft" />
              <div
                style="position: absolute; bottom: 10px; left: 20px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end; margin-top: 20px;">
                <div style="display: flex; align-items: flex-end;">
                  签名：
                  <SignatureField label="签名3" sign-type="sign3" :img-url="form.img3"
                    @update:imgUrl="form.img3 = $event" />
                </div>
                <div>
                  <editable-textarea :text="form.date4" param-type="YYYYMMDD4"
                    @send-to-parent="receiveFromChild"></editable-textarea>
                </div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import EditableTextarea from "@/views/template/EditableTextarea";
import { agencyName, sealName } from "../../utils/publicName.js";

import SignatureField from "@/views/template/SignatureField";
import { createInputLimiter } from '@/utils/limitInput';


export default {
  components: {
    EditableTextarea,
    SignatureField,
  },

  data() {
    return {
      agencyName: agencyName,
      sealName: sealName,
      form: {},
      isPdfExport: false, // 控制打印样式
      textarea4Config: {
        maxLines: 4,
        charsPerLine: 27 * 2,
        maxLength: 4 * 27 * 2,
        inputLimiter: null,
        displayText: ''
      },
      textarea5Config: {
        maxLines: 4,
        charsPerLine: 27 * 2,
        maxLength: 4 * 27 * 2,
        inputLimiter: null,
        displayText: ''
      },
      textarea6Config: {
        maxLines: 3,
        charsPerLine: 27 * 2,
        maxLength: 3 * 27 * 2,
        inputLimiter: null,
        displayText: ''
      },
    };
  },
  created() {
    //调用父页面函数获取文书数据
    window.parent.getTemplateData((data) => {
      this.form = data;
    })
    //将方法暴露在初始化加载中
    window.postForm = () => {
      this.postForm();
    }
    this.textarea4Config.inputLimiter = createInputLimiter(this, {
      maxLines: this.textarea4Config.maxLines,
      charsPerLine: this.textarea4Config.charsPerLine,
      maxLength: this.textarea4Config.maxLength,
      propName: 'form.textarea4'
    });
    this.textarea5Config.inputLimiter = createInputLimiter(this, {
      maxLines: this.textarea5Config.maxLines,
      charsPerLine: this.textarea5Config.charsPerLine,
      maxLength: this.textarea5Config.maxLength,
      propName: 'form.textarea5'
    });
    this.textarea6Config.inputLimiter = createInputLimiter(this, {
      maxLines: this.textarea6Config.maxLines,
      charsPerLine: this.textarea6Config.charsPerLine,
      maxLength: this.textarea6Config.maxLength,
      propName: 'form.textarea6'
    });

  },
  //能否编辑判断
  mounted() {
    window.parent.changeTemplateDow();
  },
  methods: {
    handleTdClick(event, value, name) {
      // 找到对应的 radio 并设置值
      this.form[name] = value;
    },
    getConfigName(field) {
      switch (field) {
        case 'textarea4':
          return this.textarea4Config;
        case 'textarea5':
          return this.textarea5Config;
        case 'textarea6':
          return this.textarea6Config;
      }
    },
    handleKeyDown(field, e) {
      const config = this.getConfigName(field);
      config.inputLimiter.handleKeyDown(e);
    },
    handleInput(field, value) {
      const config = this.getConfigName(field);
      this.form[field] = config.inputLimiter.handleInput(value);
    },
    handlePaste(field, e) {
      const config = this.getConfigName(field);
      config.inputLimiter.handlePaste(e);
    },
    // 导出为pdf
    exportPDF() {
      this.savePDF()
        .then((blob) => {
          const blobUrl = URL.createObjectURL(blob);

          // 先预览
          const previewWindow = window.open(blobUrl, '_blank');

          // 自动下载
          const fileName = `行政处罚决定法制审核意见表.pdf`;
          const downloadLink = document.createElement('a');
          downloadLink.href = blobUrl;
          downloadLink.download = fileName;
          document.body.appendChild(downloadLink);
          downloadLink.click();
          document.body.removeChild(downloadLink);

          // 监听预览窗口关闭后释放内存
          if (previewWindow) {
            const timer = setInterval(() => {
              if (previewWindow.closed) {
                clearInterval(timer);
                URL.revokeObjectURL(blobUrl);
              }
            }, 1000);
          } else {
            setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); // 兜底释放
          }
        })
        .catch(error => {
          console.error('导出PDF出错:', error);
          alert('导出失败，请重试或联系管理员');
        });
    },
    savePDF() {
      this.isPdfExport = true; // 激活PDF样式
      return new Promise((resolve, reject) => {
        this.$nextTick(() => {
          import('html2pdf.js').then((module) => {
            const html2pdf = module.default;

            //获取所有需要替换的 el-input
            const elInputs = document.querySelectorAll('.el-input__inner, .el-textarea__inner');

            //存储原始元素和它们的父节点，方便后续恢复
            const originalElements = [];

            elInputs.forEach((input) => {
              const div = document.createElement('div');
              div.style.whiteSpace = 'pre-wrap'; // 保留换行
              div.style.fontFamily = '仿宋';
              div.style.fontSize = '5mm';
              div.textContent = input.value; // 保留原内容（自动处理 \n 换行）
              div.style.lineHeight = '1.3';

              // 替换 el-input，并存储原始元素
              originalElements.push({
                parent: input.parentNode,
                original: input,
                replacement: div,
              });
              input.parentNode.replaceChild(div, input);
            });

            // 配置选项
            const opt = {
              margin: 0,
              image: {
                type: 'jpeg',
                quality: 0.98
              },
              html2canvas: {
                scale: 2,
                logging: false,
                useCORS: true
              },
              jsPDF: {
                unit: 'mm',
                format: 'a4',
                orientation: 'portrait'
              }
            };

            const element = document.getElementById('pdfDom');

            // 生成PDF Blob对象
            html2pdf()
              .set(opt)
              .from(element)
              .toPdf()
              .get('pdf')
              .then((pdf) => {
                const blob = pdf.output('blob');

                resolve(blob); // 返回Blob对象
              })
              .catch((error) => {
                reject(error);
              })
              .finally(() => {
                this.isPdfExport = false; // 恢复原始样式
                // 恢复原始input
                originalElements.forEach(({ parent, original, replacement }) => {
                  parent.replaceChild(original, replacement);
                });
              });
          }).catch((error) => {
            reject(error);
            this.isPdfExport = false;
            originalElements.forEach(({ parent, original, replacement }) => {
              parent.replaceChild(original, replacement);
            });
          });
        });
      });
    },
    //父页面提交按钮将调用此方法，此方法将文书数据回传到父页面的请求方法中
    postForm() {
      this.savePDF()
        .then((blob) => {


          // 创建FormData并添加文件
          const formData = new FormData();
          formData.append('file', blob, '行政处罚决定法制审核意见表.pdf');

          window.parent.postTemplateDate(this.form, formData);
        })
        .catch(error => {
          console.error('整个保存PDF出错:', error);
        });
    },
    //选择日期时间
    receiveFromChild(data, type) {
      const TypeMap = {
        'YYYYMMDD1': 'date1',
        'YYYYMMDD2': 'date2',
        'YYYYMMDD3': 'date3',
        'YYYYMMDD4': 'date4',
      };
      if (TypeMap[type]) {
        this.form[TypeMap[type]] = data;
      }
    },
  },
};
</script>

<style scoped>
/* 让 td 可以点击 */
td {
  cursor: pointer;
  position: relative;
}

:deep(.el-button-print .el-button) {
  display: inline-flex !important;
  visibility: visible !important;
  opacity: 1 !important;
  width: auto;
  min-width: 100px;
  height: auto;
  padding: 8px 15px;
  background: #fff !important;
  color: #000 !important;
  border: none;
}

:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden;
  line-height: 1.3;
}

:deep(.el-textarea-hidden .el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden !important;
  resize: none !important;
  height: auto !important;
}

.input-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

.inputStyleNoLine {
  border: none;
  outline: none;
  padding: 0px;
}

.typeSpan {
  cursor: pointer;
  font-size: 5mm;
}
</style>
